import { removeItem, sessionRemoveItem } from './../../utils/auth'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'

import { RootState } from '../index'
import { LoginFormType } from '@/interfaces/PagesType/LoginType'
import { sessionGetItem, sessionSetItem } from '@/utils/auth'
interface InitialStateType {
  user: LoginFormType
  token: string
  loading: boolean
  isCollapsed: boolean
  isopen_key: string[]
}
// 使用该类型定义初始 state
const initialState: InitialStateType = {
  user: {
    username: '',
    password: '',
    repassword: '',
    remember: true
  },
  token: '',
  loading: false,
  isCollapsed: sessionGetItem('Collapsed'),
  isopen_key: ['']
}
const user = createSlice({
  name: 'user',
  initialState,
  reducers: {
    getToken(state, action: PayloadAction<string>) {
      state.token = action.payload
      sessionSetItem('token', state.token)
    },
    getUser(state, action: PayloadAction<LoginFormType>) {
      state.user = action.payload
      sessionSetItem('username', state.user.username)
    },
    changeLoading(state, action: PayloadAction<boolean>) {
      state.loading = action.payload
    },
    setCollapsed(state, action: PayloadAction<boolean>) {
      state.isCollapsed = action.payload
      sessionSetItem('Collapsed', action.payload)
    },
    setKeys(state, action: PayloadAction<string[]>) {
      state.isopen_key = action.payload
    },
    // 退出
    logout() {
      sessionRemoveItem('token')
      sessionRemoveItem('username')
      removeItem('lang')
      location.reload()
    }
  }
})
// 导出state
export const user_admin = (state: RootState) => state.user.user
export const token = (state: RootState) => state.user.token
export const loading = (state: RootState) => state.user.loading
export const isCollapsed = (state: RootState) => state.user.isCollapsed
export const isopen_key = (state: RootState) => state.user.isopen_key
// 导出actions
export const { getToken, getUser, changeLoading, setCollapsed, setKeys, logout } = user.actions
export default user.reducer
